package com.zheng.pvz.view
{
	import flash.display.Sprite;
	
	/**
	 * 基础控制类 
	 * @author Administrator
	 * 
	 */
	public class BaseObject extends Sprite
	{
		//该容器中的显示对象列表
		private var baseObjects:Array;
		//待添加对象数组
		private var objectsToAdd:Array;
		//待删除对象数组
		private var objectsToRemove:Array;
		//层级关系
		public var drawPriority:int;
		
		public function BaseObject()
		{
			this.baseObjects=new Array();
			this.objectsToAdd=new Array();
			this.objectsToRemove=new Array();
			
		}
		/**
		 * 每次帧变动的时候执行 
		 * 递归到子对象
		 * @param timeSpan
		 * 
		 */
		public function tickBase(timeSpan:uint):void{
			for each(var i:BaseObject in baseObjects){
				i.tickBase(timeSpan);
			}
			this.addAndRemoveObject();
			tick(timeSpan);
		}
		/**
		 * 每次帧变动的时候执行，子类覆写 
		 * @param timeSpan
		 * 
		 */
		
		public function tick(timeSpan:uint):void{
		}
		/**
		 * 帧变动的时候，做添加、删除对象的操作
		 * 主要用于避免，两帧间隔时间内，同一个对象被移除又添加，或者先被添加又移除 
		 * 
		 */
		public function addAndRemoveObject():void{
			var obj:BaseObject;
			var index:int;
			var isPrio:Boolean;

			//删除
			if(this.objectsToRemove.length>0){
				for each(var i:BaseObject in this.objectsToRemove){
					obj=i;
					index=this.baseObjects.indexOf(obj);
					if(index!=-1){
						this.baseObjects.splice(index,1);
					}
					if(obj.parent!=null&&obj.parent==this){
						this.removeChild(obj);
					}
				}
				this.objectsToRemove.splice(0,this.objectsToRemove.length);
			}
			//添加
			if(this.objectsToAdd.length>0){
				
				for each(var k:BaseObject in this.objectsToAdd){
					isPrio=false;
					for (var j:int = 0; j < baseObjects.length; j++ )
					{
						if (k.drawPriority < baseObjects[j].drawPriority)
						{
							addChildAt(k, getChildIndex(baseObjects[j]));
							baseObjects.splice(j, 0, k);
							isPrio = true;
							break;
						}
					}
					if (!isPrio){
						baseObjects.push(k);
						addChild(k);
					}
				}
				this.objectsToAdd.splice(0, objectsToAdd.length);
			}
		}
		/**
		 * 将要添加的对象放到objectsToAdd数组中，做临时的存储
		 * 帧变动时才通过addAndRemoveObject方法添加到显示列表中
		 * @param obj
		 * 
		 */
		public function addObject(obj:BaseObject):void{
			if(obj==null)return ;
			var removeIndex:int=this.objectsToRemove.indexOf(obj);
			if(removeIndex!=-1){
				this.objectsToRemove.splice(removeIndex,1);
			}else if(this.objectsToAdd.indexOf(obj)==-1&&this.baseObjects.indexOf(obj)==-1){
				this.objectsToAdd.push(obj);
				if(obj.parent!=null&&obj.parent==this){
					this.removeChild(obj);
				}
			}
		}
		/**
		 * 同addObject 
		 * @param obj
		 * 
		 */
		public function removeObject(obj:BaseObject):void{
			if(obj==null)return ;
			var removeIndex:int=this.objectsToAdd.indexOf(obj);
			if(removeIndex!=-1){
				this.objectsToAdd.splice(removeIndex,1);
			}else if(this.objectsToRemove.indexOf(obj)==-1&&this.baseObjects.indexOf(obj)!=-1){
				this.objectsToRemove.push(obj);
			}
		}
	}
}